package cn.zorbus.laian.infrastructure.bus;

import cn.zorbus.laian.infrastructure.config.IndustrialControlProperties;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * create in 2023/12/26 22:38
 *
 * @author shishaodong
 * @version 0.0.1
 */
@Slf4j
@Component
public class UdpEventBus {

    @Resource
    private IndustrialControlProperties controlProperties;

    @SneakyThrows
    public void sentEvent(@NotNull String message) {
        try (DatagramSocket socket = new DatagramSocket()) {
            // Prepare the data to be sent
            byte[] sendData = message.getBytes(StandardCharsets.UTF_8);
            InetAddress serverAddress = InetAddress.getByName(controlProperties.getHostname());
            // Create a DatagramPacket with the data to be sent
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, controlProperties.getPort());
            // Send the packet
            socket.send(sendPacket);
            log.debug("Sent message to {} - {}:{}", message, controlProperties.getHostname(), controlProperties.getPort());
        }
    }
}
